/**
 * 报告生成管理器 - 负责报告生成页面的交互功能
 * 包含报告模板管理、AI生成报告、报告预览、导出等功能
 */
class ReportGenerationManager {
    constructor() {
        this.templates = [];
        this.reports = [];
        this.currentTemplate = null;
        this.generationProgress = 0;
        this.selectedReports = new Set();
        this.filters = {
            type: '',
            timeRange: 'month',
            status: '',
            keyword: ''
        };
        this.pagination = {
            page: 1,
            pageSize: 10,
            total: 0
        };
        
        this.init();
    }

    /**
     * 初始化报告生成管理器
     */
    init() {
        this.loadTemplates();
        this.loadReports();
        this.bindEvents();
        this.initializeCharts();
    }

    /**
     * 绑定事件处理
     */
    bindEvents() {
        // 模板选择
        document.getElementById('templateSelect')?.addEventListener('change', (e) => {
            this.selectTemplate(e.target.value);
        });

        // 筛选器事件
        document.getElementById('reportTypeFilter')?.addEventListener('change', (e) => {
            this.filters.type = e.target.value;
            this.applyFilters();
        });

        document.getElementById('timeRangeFilter')?.addEventListener('change', (e) => {
            this.filters.timeRange = e.target.value;
            this.applyFilters();
        });

        document.getElementById('statusFilter')?.addEventListener('change', (e) => {
            this.filters.status = e.target.value;
            this.applyFilters();
        });

        // 搜索事件
        const searchInput = document.getElementById('searchInput');
        let searchTimeout;
        searchInput?.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.filters.keyword = e.target.value;
                this.applyFilters();
            }, 500);
        });

        // 按钮事件
        document.getElementById('generateReportBtn')?.addEventListener('click', () => {
            this.showGenerateModal();
        });

        document.getElementById('createTemplateBtn')?.addEventListener('click', () => {
            this.showTemplateModal();
        });

        document.getElementById('refreshBtn')?.addEventListener('click', () => {
            this.loadReports();
            this.showNotification('报告列表已刷新', 'success');
        });

        // 分页事件
        document.getElementById('prevPage')?.addEventListener('click', () => {
            if (this.pagination.page > 1) {
                this.pagination.page--;
                this.loadReports();
            }
        });

        document.getElementById('nextPage')?.addEventListener('click', () => {
            if (this.pagination.page < this.getTotalPages()) {
                this.pagination.page++;
                this.loadReports();
            }
        });

        // 批量操作
        document.getElementById('selectAll')?.addEventListener('change', (e) => {
            this.toggleSelectAll(e.target.checked);
        });

        document.getElementById('batchDelete')?.addEventListener('click', () => {
            this.batchDeleteReports();
        });

        document.getElementById('batchExport')?.addEventListener('click', () => {
            this.batchExportReports();
        });

        // 报告列表事件（事件委托）
        document.getElementById('reportsList')?.addEventListener('click', (e) => {
            const reportRow = e.target.closest('.report-row');
            if (!reportRow) return;

            const reportId = reportRow.dataset.reportId;

            // 预览报告
            if (e.target.closest('.preview-btn')) {
                e.preventDefault();
                this.previewReport(reportId);
            }

            // 下载报告
            if (e.target.closest('.download-btn')) {
                e.preventDefault();
                this.downloadReport(reportId);
            }

            // 编辑报告
            if (e.target.closest('.edit-btn')) {
                e.preventDefault();
                this.editReport(reportId);
            }

            // 删除报告
            if (e.target.closest('.delete-btn')) {
                e.preventDefault();
                this.deleteReport(reportId);
            }

            // 选择报告
            if (e.target.closest('.report-checkbox')) {
                this.toggleReportSelection(reportId, e.target.checked);
            }
        });

        // 模板列表事件
        document.getElementById('templatesList')?.addEventListener('click', (e) => {
            const templateRow = e.target.closest('.template-row');
            if (!templateRow) return;

            const templateId = templateRow.dataset.templateId;

            // 使用模板
            if (e.target.closest('.use-template-btn')) {
                e.preventDefault();
                this.useTemplate(templateId);
            }

            // 编辑模板
            if (e.target.closest('.edit-template-btn')) {
                e.preventDefault();
                this.editTemplate(templateId);
            }

            // 删除模板
            if (e.target.closest('.delete-template-btn')) {
                e.preventDefault();
                this.deleteTemplate(templateId);
            }
        });

        // AI生成配置
        document.getElementById('aiGenerateBtn')?.addEventListener('click', () => {
            this.generateAIReport();
        });

        document.getElementById('aiConfigBtn')?.addEventListener('click', () => {
            this.showAIConfigModal();
        });
    }

    /**
     * 加载报告模板
     */
    async loadTemplates() {
        try {
            const response = await fetch('/api/reports/templates');
            const result = await response.json();

            if (result.code === 200) {
                this.templates = result.data;
                this.renderTemplates();
                this.updateTemplateSelect();
            } else {
                this.showNotification('加载模板失败', 'error');
            }
        } catch (error) {
            console.error('加载模板出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 加载报告列表
     */
    async loadReports() {
        try {
            const params = new URLSearchParams({
                page: this.pagination.page,
                page_size: this.pagination.pageSize,
                ...this.filters
            });

            const response = await fetch(`/api/reports?${params}`);
            const result = await response.json();

            if (result.code === 200) {
                this.reports = result.data.reports;
                this.pagination.total = result.data.total;
                this.renderReports();
                this.updatePagination();
            } else {
                this.showNotification('加载报告失败', 'error');
            }
        } catch (error) {
            console.error('加载报告出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 渲染模板列表
     */
    renderTemplates() {
        const container = document.getElementById('templatesList');
        if (!container) return;

        if (this.templates.length === 0) {
            container.innerHTML = `
                <div class="text-center py-8 text-slate-500">
                    <i class="fas fa-file-alt text-4xl mb-4"></i>
                    <p>暂无报告模板</p>
                    <button class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" onclick="reportGenerationManager.showTemplateModal()">
                        创建模板
                    </button>
                </div>
            `;
            return;
        }

        const html = this.templates.map(template => `
            <div class="template-row border border-slate-200 rounded-lg p-4 hover:bg-slate-50" data-template-id="${template.id}">
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-medium text-slate-800">${template.name}</h4>
                    <div class="flex space-x-2">
                        <button class="use-template-btn text-blue-600 hover:text-blue-800 text-sm">
                            <i class="fas fa-play mr-1"></i>使用
                        </button>
                        <button class="edit-template-btn text-green-600 hover:text-green-800 text-sm">
                            <i class="fas fa-edit mr-1"></i>编辑
                        </button>
                        <button class="delete-template-btn text-red-600 hover:text-red-800 text-sm">
                            <i class="fas fa-trash mr-1"></i>删除
                        </button>
                    </div>
                </div>
                <p class="text-sm text-slate-600 mb-2">${template.description}</p>
                <div class="flex items-center justify-between text-xs text-slate-500">
                    <span>类型: ${template.type}</span>
                    <span>更新时间: ${new Date(template.updated_at).toLocaleDateString('zh-CN')}</span>
                </div>
            </div>
        `).join('');

        container.innerHTML = html;
    }

    /**
     * 渲染报告列表
     */
    renderReports() {
        const container = document.getElementById('reportsList');
        if (!container) return;

        if (this.reports.length === 0) {
            container.innerHTML = `
                <div class="text-center py-12 text-slate-500">
                    <i class="fas fa-file-alt text-4xl mb-4"></i>
                    <p>暂无报告数据</p>
                    <button class="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" onclick="reportGenerationManager.showGenerateModal()">
                        生成报告
                    </button>
                </div>
            `;
            return;
        }

        const html = this.reports.map(report => `
            <tr class="report-row hover:bg-slate-50" data-report-id="${report.id}">
                <td class="p-4">
                    <input type="checkbox" class="report-checkbox rounded" 
                           ${this.selectedReports.has(report.id) ? 'checked' : ''}>
                </td>
                <td class="p-4">
                    <div class="max-w-xs">
                        <p class="text-sm font-medium text-slate-800">${report.title}</p>
                        <p class="text-xs text-slate-500 mt-1">${report.description}</p>
                    </div>
                </td>
                <td class="p-4">
                    ${this.getReportTypeBadge(report.type)}
                </td>
                <td class="p-4">
                    <span class="text-sm text-slate-600">${new Date(report.created_at).toLocaleDateString('zh-CN')}</span>
                </td>
                <td class="p-4">
                    ${this.getReportStatusBadge(report.status)}
                </td>
                <td class="p-4">
                    <div class="flex items-center space-x-2">
                        <span class="text-sm text-slate-600">${this.formatFileSize(report.file_size)}</span>
                        ${report.status === 'generating' ? `
                            <div class="w-16 bg-slate-200 rounded-full h-2">
                                <div class="bg-blue-600 h-2 rounded-full" style="width: ${report.progress || 0}%"></div>
                            </div>
                        ` : ''}
                    </div>
                </td>
                <td class="p-4">
                    <div class="flex space-x-2">
                        <button class="preview-btn text-blue-600 hover:text-blue-800 text-sm" 
                                ${report.status !== 'completed' ? 'disabled' : ''}>
                            <i class="fas fa-eye"></i>
                        </button>
                        <button class="download-btn text-green-600 hover:text-green-800 text-sm"
                                ${report.status !== 'completed' ? 'disabled' : ''}>
                            <i class="fas fa-download"></i>
                        </button>
                        <button class="edit-btn text-yellow-600 hover:text-yellow-800 text-sm">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="delete-btn text-red-600 hover:text-red-800 text-sm">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `).join('');

        container.innerHTML = html;
    }

    /**
     * 获取报告类型标签
     */
    getReportTypeBadge(type) {
        const badges = {
            'summary': '<span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">汇总报告</span>',
            'detailed': '<span class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">详细报告</span>',
            'statistical': '<span class="px-2 py-1 bg-purple-100 text-purple-700 text-xs rounded-full">统计报告</span>',
            'analysis': '<span class="px-2 py-1 bg-orange-100 text-orange-700 text-xs rounded-full">分析报告</span>'
        };
        return badges[type] || badges['summary'];
    }

    /**
     * 获取报告状态标签
     */
    getReportStatusBadge(status) {
        const badges = {
            'pending': '<span class="px-2 py-1 bg-yellow-100 text-yellow-700 text-xs rounded-full">待生成</span>',
            'generating': '<span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded-full">生成中</span>',
            'completed': '<span class="px-2 py-1 bg-green-100 text-green-700 text-xs rounded-full">已完成</span>',
            'failed': '<span class="px-2 py-1 bg-red-100 text-red-700 text-xs rounded-full">失败</span>'
        };
        return badges[status] || badges['pending'];
    }

    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
        if (!bytes) return '-';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    /**
     * 更新模板选择器
     */
    updateTemplateSelect() {
        const select = document.getElementById('templateSelect');
        if (!select) return;

        const html = this.templates.map(template => 
            `<option value="${template.id}">${template.name}</option>`
        ).join('');

        select.innerHTML = '<option value="">选择模板</option>' + html;
    }

    /**
     * 选择模板
     */
    selectTemplate(templateId) {
        this.currentTemplate = this.templates.find(t => t.id === templateId);
        if (this.currentTemplate) {
            this.showNotification(`已选择模板: ${this.currentTemplate.name}`, 'success');
        }
    }

    /**
     * 使用模板
     */
    useTemplate(templateId) {
        const template = this.templates.find(t => t.id === templateId);
        if (template) {
            this.currentTemplate = template;
            document.getElementById('templateSelect').value = templateId;
            this.showNotification(`已选择模板: ${template.name}`, 'success');
        }
    }

    /**
     * 显示生成报告模态框
     */
    showGenerateModal() {
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="generateModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">生成报告</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="reportGenerationManager.closeModal('generateModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <form id="generateReportForm" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">报告标题</label>
                            <input type="text" id="reportTitle" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">报告描述</label>
                            <textarea id="reportDescription" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                        </div>
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">报告类型</label>
                                <select id="reportType" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                                    <option value="summary">汇总报告</option>
                                    <option value="detailed">详细报告</option>
                                    <option value="statistical">统计报告</option>
                                    <option value="analysis">分析报告</option>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">时间范围</label>
                                <select id="reportTimeRange" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                                    <option value="today">今天</option>
                                    <option value="week">本周</option>
                                    <option value="month">本月</option>
                                    <option value="quarter">本季度</option>
                                    <option value="year">本年</option>
                                    <option value="custom">自定义</option>
                                </select>
                            </div>
                        </div>
                        
                        <div id="customDateRange" class="hidden grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
                                <input type="date" id="startDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
                                <input type="date" id="endDate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">选择模板</label>
                            <select id="templateSelect" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="">不使用模板</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">包含数据</label>
                            <div class="space-y-2">
                                <label class="flex items-center">
                                    <input type="checkbox" class="mr-2" value="statistics" checked>
                                    <span class="text-sm">统计数据</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" class="mr-2" value="charts" checked>
                                    <span class="text-sm">图表分析</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" class="mr-2" value="trends" checked>
                                    <span class="text-sm">趋势分析</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="checkbox" class="mr-2" value="recommendations">
                                    <span class="text-sm">建议措施</span>
                                </label>
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">生成方式</label>
                            <div class="flex space-x-4">
                                <label class="flex items-center">
                                    <input type="radio" name="generateMethod" value="standard" class="mr-2" checked>
                                    <span class="text-sm">标准生成</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="radio" name="generateMethod" value="ai" class="mr-2">
                                    <span class="text-sm">AI智能生成</span>
                                </label>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="reportGenerationManager.closeModal('generateModal')">取消</button>
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">生成报告</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 更新模板选择器
        this.updateTemplateSelectInModal();
        
        // 绑定表单事件
        this.bindGenerateFormEvents();
    }

    /**
     * 更新模态框中的模板选择器
     */
    updateTemplateSelectInModal() {
        const select = document.querySelector('#generateModal #templateSelect');
        if (!select) return;

        const html = this.templates.map(template => 
            `<option value="${template.id}">${template.name}</option>`
        ).join('');

        select.innerHTML = '<option value="">不使用模板</option>' + html;
    }

    /**
     * 绑定生成表单事件
     */
    bindGenerateFormEvents() {
        const form = document.getElementById('generateReportForm');
        const timeRangeSelect = document.getElementById('reportTimeRange');
        const customDateRange = document.getElementById('customDateRange');

        // 时间范围选择
        timeRangeSelect?.addEventListener('change', (e) => {
            if (e.target.value === 'custom') {
                customDateRange.classList.remove('hidden');
            } else {
                customDateRange.classList.add('hidden');
            }
        });

        // 表单提交
        form?.addEventListener('submit', (e) => {
            e.preventDefault();
            this.generateReport(form);
        });
    }

    /**
     * 生成报告
     */
    async generateReport(form) {
        const formData = new FormData(form);
        const reportData = {
            title: formData.get('reportTitle') || document.getElementById('reportTitle').value,
            description: formData.get('reportDescription') || document.getElementById('reportDescription').value,
            type: formData.get('reportType') || document.getElementById('reportType').value,
            time_range: formData.get('reportTimeRange') || document.getElementById('reportTimeRange').value,
            template_id: document.getElementById('templateSelect').value || null,
            include_data: this.getCheckedData(),
            generate_method: formData.get('generateMethod')
        };

        // 添加自定义日期范围
        if (reportData.time_range === 'custom') {
            reportData.start_date = document.getElementById('startDate').value;
            reportData.end_date = document.getElementById('endDate').value;
        }

        try {
            const response = await fetch('/api/reports/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(reportData)
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('报告生成任务已提交', 'success');
                this.closeModal('generateModal');
                this.loadReports();
                
                // 如果是AI生成，显示进度
                if (reportData.generate_method === 'ai') {
                    this.startProgressMonitoring(result.data.task_id);
                }
            } else {
                this.showNotification(result.message || '报告生成失败', 'error');
            }
        } catch (error) {
            console.error('生成报告出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 获取选中的数据
     */
    getCheckedData() {
        const checkboxes = document.querySelectorAll('#generateModal input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    /**
     * 开始进度监控
     */
    startProgressMonitoring(taskId) {
        const checkProgress = async () => {
            try {
                const response = await fetch(`/api/reports/progress/${taskId}`);
                const result = await response.json();

                if (result.code === 200) {
                    const progress = result.data.progress;
                    this.updateGenerationProgress(progress);

                    if (progress < 100) {
                        setTimeout(checkProgress, 2000);
                    } else {
                        this.loadReports();
                        this.showNotification('报告生成完成', 'success');
                    }
                }
            } catch (error) {
                console.error('检查进度出错:', error);
            }
        };

        checkProgress();
    }

    /**
     * 更新生成进度
     */
    updateGenerationProgress(progress) {
        // 更新进度条
        const progressBar = document.querySelector('.generation-progress .progress-bar');
        if (progressBar) {
            progressBar.style.width = `${progress}%`;
        }

        // 更新进度文本
        const progressText = document.querySelector('.generation-progress .progress-text');
        if (progressText) {
            progressText.textContent = `${progress}%`;
        }
    }

    /**
     * 显示模板模态框
     */
    showTemplateModal(template = null) {
        const isEdit = !!template;
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="templateModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">${isEdit ? '编辑模板' : '创建模板'}</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="reportGenerationManager.closeModal('templateModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <form id="templateForm" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">模板名称</label>
                            <input type="text" id="templateName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" value="${template?.name || ''}" required>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">模板描述</label>
                            <textarea id="templateDescription" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">${template?.description || ''}</textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">模板类型</label>
                            <select id="templateType" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required>
                                <option value="summary" ${template?.type === 'summary' ? 'selected' : ''}>汇总报告</option>
                                <option value="detailed" ${template?.type === 'detailed' ? 'selected' : ''}>详细报告</option>
                                <option value="statistical" ${template?.type === 'statistical' ? 'selected' : ''}>统计报告</option>
                                <option value="analysis" ${template?.type === 'analysis' ? 'selected' : ''}>分析报告</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">模板内容</label>
                            <textarea id="templateContent" rows="10" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm" placeholder="使用 {{variable}} 语法插入变量，如 {{title}}、{{statistics}} 等">${template?.content || ''}</textarea>
                        </div>
                        
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <h4 class="font-medium text-gray-700 mb-2">可用变量</h4>
                            <div class="grid grid-cols-2 gap-2 text-sm text-gray-600">
                                <div><code>{{title}}</code> - 报告标题</div>
                                <div><code>{{description}}</code> - 报告描述</div>
                                <div><code>{{generated_at}}</code> - 生成时间</div>
                                <div><code>{{statistics}}</code> - 统计数据</div>
                                <div><code>{{charts}}</code> - 图表数据</div>
                                <div><code>{{trends}}</code> - 趋势分析</div>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-3 pt-4">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="reportGenerationManager.closeModal('templateModal')">取消</button>
                            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">${isEdit ? '更新' : '创建'}</button>
                        </div>
                    </form>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 绑定表单提交事件
        const form = document.getElementById('templateForm');
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            this.saveTemplate(form, template?.id);
        });
    }

    /**
     * 保存模板
     */
    async saveTemplate(form, templateId = null) {
        const templateData = {
            name: document.getElementById('templateName').value,
            description: document.getElementById('templateDescription').value,
            type: document.getElementById('templateType').value,
            content: document.getElementById('templateContent').value
        };

        try {
            const url = templateId ? `/api/reports/templates/${templateId}` : '/api/reports/templates';
            const method = templateId ? 'PUT' : 'POST';

            const response = await fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(templateData)
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification(templateId ? '模板更新成功' : '模板创建成功', 'success');
                this.closeModal('templateModal');
                this.loadTemplates();
            } else {
                this.showNotification(result.message || '模板保存失败', 'error');
            }
        } catch (error) {
            console.error('保存模板出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 编辑模板
     */
    editTemplate(templateId) {
        const template = this.templates.find(t => t.id === templateId);
        if (template) {
            this.showTemplateModal(template);
        }
    }

    /**
     * 删除模板
     */
    async deleteTemplate(templateId) {
        if (!confirm('确定要删除这个模板吗？')) return;

        try {
            const response = await fetch(`/api/reports/templates/${templateId}`, {
                method: 'DELETE'
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('模板删除成功', 'success');
                this.loadTemplates();
            } else {
                this.showNotification(result.message || '模板删除失败', 'error');
            }
        } catch (error) {
            console.error('删除模板出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 预览报告
     */
    previewReport(reportId) {
        const report = this.reports.find(r => r.id === reportId);
        if (!report) return;

        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="previewModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">预览报告</h3>
                        <div class="flex space-x-2">
                            <button class="text-blue-600 hover:text-blue-800" onclick="reportGenerationManager.downloadReport('${reportId}')">
                                <i class="fas fa-download mr-1"></i>下载
                            </button>
                            <button class="text-gray-500 hover:text-gray-700" onclick="reportGenerationManager.closeModal('previewModal')">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="bg-gray-50 p-6 rounded-lg">
                        <h2 class="text-xl font-bold mb-4">${report.title}</h2>
                        <p class="text-gray-600 mb-4">${report.description}</p>
                        <div class="text-sm text-gray-500 mb-6">
                            <span>生成时间: ${new Date(report.created_at).toLocaleString('zh-CN')}</span>
                            <span class="ml-4">类型: ${this.getReportTypeName(report.type)}</span>
                        </div>
                        
                        <div class="bg-white p-4 rounded-lg border">
                            <p class="text-center text-gray-500">报告内容预览区域</p>
                            <p class="text-center text-gray-400 text-sm mt-2">完整报告请下载后查看</p>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }

    /**
     * 获取报告类型名称
     */
    getReportTypeName(type) {
        const names = {
            'summary': '汇总报告',
            'detailed': '详细报告',
            'statistical': '统计报告',
            'analysis': '分析报告'
        };
        return names[type] || '未知类型';
    }

    /**
     * 下载报告
     */
    async downloadReport(reportId) {
        const report = this.reports.find(r => r.id === reportId);
        if (!report) return;

        try {
            const response = await fetch(`/api/reports/${reportId}/download`);
            
            if (response.ok) {
                const blob = await response.blob();
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = report.title + '.pdf';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                this.showNotification('报告下载成功', 'success');
            } else {
                this.showNotification('报告下载失败', 'error');
            }
        } catch (error) {
            console.error('下载报告出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 编辑报告
     */
    editReport(reportId) {
        const report = this.reports.find(r => r.id === reportId);
        if (!report) return;

        // 填充生成表单
        this.showGenerateModal();
        
        // 延迟填充表单数据
        setTimeout(() => {
            document.getElementById('reportTitle').value = report.title;
            document.getElementById('reportDescription').value = report.description;
            document.getElementById('reportType').value = report.type;
        }, 100);
    }

    /**
     * 删除报告
     */
    async deleteReport(reportId) {
        if (!confirm('确定要删除这个报告吗？')) return;

        try {
            const response = await fetch(`/api/reports/${reportId}`, {
                method: 'DELETE'
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('报告删除成功', 'success');
                this.loadReports();
            } else {
                this.showNotification(result.message || '报告删除失败', 'error');
            }
        } catch (error) {
            console.error('删除报告出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 切换全选
     */
    toggleSelectAll(checked) {
        this.reports.forEach(report => {
            if (checked) {
                this.selectedReports.add(report.id);
            } else {
                this.selectedReports.delete(report.id);
            }
        });
        this.renderReports();
    }

    /**
     * 切换单个报告选择
     */
    toggleReportSelection(reportId, checked) {
        if (checked) {
            this.selectedReports.add(reportId);
        } else {
            this.selectedReports.delete(reportId);
        }
    }

    /**
     * 批量删除报告
     */
    async batchDeleteReports() {
        if (this.selectedReports.size === 0) {
            this.showNotification('请选择要删除的报告', 'warning');
            return;
        }

        if (!confirm(`确定要删除选中的 ${this.selectedReports.size} 个报告吗？`)) return;

        try {
            const response = await fetch('/api/reports/batch-delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    report_ids: Array.from(this.selectedReports)
                })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('批量删除成功', 'success');
                this.selectedReports.clear();
                this.loadReports();
            } else {
                this.showNotification(result.message || '批量删除失败', 'error');
            }
        } catch (error) {
            console.error('批量删除出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 批量导出报告
     */
    batchExportReports() {
        if (this.selectedReports.size === 0) {
            this.showNotification('请选择要导出的报告', 'warning');
            return;
        }

        // 逐个下载选中的报告
        this.selectedReports.forEach(reportId => {
            this.downloadReport(reportId);
        });
    }

    /**
     * 生成AI报告
     */
    async generateAIReport() {
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="aiGenerateModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-2xl">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">AI智能生成报告</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="reportGenerationManager.closeModal('aiGenerateModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">报告主题</label>
                            <input type="text" id="aiReportTopic" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="请输入报告主题或关键词">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">分析要求</label>
                            <textarea id="aiRequirements" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="描述您的分析要求，如：重点分析趋势、找出关键问题、提出改进建议等"></textarea>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">报告风格</label>
                            <select id="aiReportStyle" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="formal">正式报告</option>
                                <option value="concise">简洁报告</option>
                                <option value="detailed">详细分析</option>
                                <option value="executive">执行摘要</option>
                            </select>
                        </div>
                        
                        <div class="bg-blue-50 p-4 rounded-lg">
                            <h4 class="font-medium text-blue-800 mb-2">AI生成说明</h4>
                            <ul class="text-sm text-blue-700 space-y-1">
                                <li>• AI将基于您的主题和要求自动分析数据</li>
                                <li>• 生成过程可能需要几分钟时间</li>
                                <li>• 生成的报告包含数据分析和建议措施</li>
                                <li>• 您可以在生成后编辑和调整报告内容</li>
                            </ul>
                        </div>
                        
                        <div class="flex justify-end space-x-3">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="reportGenerationManager.closeModal('aiGenerateModal')">取消</button>
                            <button type="button" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" onclick="reportGenerationManager.startAIReportGeneration()">开始生成</button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }

    /**
     * 开始AI报告生成
     */
    async startAIReportGeneration() {
        const topic = document.getElementById('aiReportTopic').value;
        const requirements = document.getElementById('aiRequirements').value;
        const style = document.getElementById('aiReportStyle').value;

        if (!topic) {
            this.showNotification('请输入报告主题', 'warning');
            return;
        }

        try {
            const response = await fetch('/api/reports/ai-generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    topic: topic,
                    requirements: requirements,
                    style: style
                })
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.closeModal('aiGenerateModal');
                this.showNotification('AI报告生成任务已提交', 'success');
                this.loadReports();
                this.startProgressMonitoring(result.data.task_id);
            } else {
                this.showNotification(result.message || 'AI生成失败', 'error');
            }
        } catch (error) {
            console.error('AI生成出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 显示AI配置模态框
     */
    showAIConfigModal() {
        const modalHtml = `
            <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" id="aiConfigModal">
                <div class="bg-white rounded-xl p-6 w-full max-w-md">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-lg font-semibold">AI生成配置</h3>
                        <button class="text-gray-500 hover:text-gray-700" onclick="reportGenerationManager.closeModal('aiConfigModal')">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">AI模型选择</label>
                            <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="gpt-4">GPT-4</option>
                                <option value="claude">Claude</option>
                                <option value="wenxin">文心一言</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">生成质量</label>
                            <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="standard">标准</option>
                                <option value="high">高质量</option>
                                <option value="premium">优质</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">报告语言</label>
                            <select class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                                <option value="zh-CN">中文</option>
                                <option value="en">English</option>
                                <option value="both">中英双语</option>
                            </select>
                        </div>
                        
                        <div class="flex justify-end space-x-3">
                            <button type="button" class="px-4 py-2 text-gray-600 hover:text-gray-800" onclick="reportGenerationManager.closeModal('aiConfigModal')">取消</button>
                            <button type="button" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700" onclick="reportGenerationManager.saveAIConfig()">保存配置</button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.insertAdjacentHTML('beforeend', modalHtml);
    }

    /**
     * 保存AI配置
     */
    async saveAIConfig() {
        const config = {
            model: document.querySelector('#aiConfigModal select:nth-child(1)').value,
            quality: document.querySelector('#aiConfigModal select:nth-child(2)').value,
            language: document.querySelector('#aiConfigModal select:nth-child(3)').value
        };

        try {
            const response = await fetch('/api/reports/ai-config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config)
            });

            const result = await response.json();
            
            if (result.code === 200) {
                this.showNotification('AI配置保存成功', 'success');
                this.closeModal('aiConfigModal');
            } else {
                this.showNotification(result.message || '配置保存失败', 'error');
            }
        } catch (error) {
            console.error('保存AI配置出错:', error);
            this.showNotification('网络连接异常', 'error');
        }
    }

    /**
     * 应用筛选器
     */
    applyFilters() {
        this.pagination.page = 1;
        this.selectedReports.clear();
        this.loadReports();
    }

    /**
     * 更新分页显示
     */
    updatePagination() {
        const totalPages = this.getTotalPages();
        
        // 更新页码显示
        document.getElementById('currentPage')?.replaceWith(
            `<span id="currentPage">${this.pagination.page}</span>`
        );
        
        document.getElementById('totalPages')?.replaceWith(
            `<span id="totalPages">${totalPages}</span>`
        );

        // 更新按钮状态
        const prevBtn = document.getElementById('prevPage');
        const nextBtn = document.getElementById('nextPage');
        
        if (prevBtn) {
            prevBtn.disabled = this.pagination.page <= 1;
            prevBtn.classList.toggle('opacity-50', this.pagination.page <= 1);
        }
        
        if (nextBtn) {
            nextBtn.disabled = this.pagination.page >= totalPages;
            nextBtn.classList.toggle('opacity-50', this.pagination.page >= totalPages);
        }

        // 更新全选框状态
        const selectAll = document.getElementById('selectAll');
        if (selectAll) {
            const allSelected = this.reports.length > 0 && 
                this.reports.every(report => this.selectedReports.has(report.id));
            selectAll.checked = allSelected;
        }
    }

    /**
     * 获取总页数
     */
    getTotalPages() {
        return Math.ceil(this.pagination.total / this.pagination.pageSize);
    }

    /**
     * 初始化图表
     */
    initializeCharts() {
        this.initReportTypeChart();
        this.initGenerationTrendChart();
    }

    /**
     * 初始化报告类型统计图
     */
    initReportTypeChart() {
        const ctx = document.getElementById('reportTypeChart');
        if (!ctx) return;

        this.charts.reportType = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['汇总报告', '详细报告', '统计报告', '分析报告'],
                datasets: [{
                    data: [45, 30, 20, 15],
                    backgroundColor: [
                        'rgba(59, 130, 246, 0.8)',
                        'rgba(16, 185, 129, 0.8)',
                        'rgba(245, 158, 11, 0.8)',
                        'rgba(139, 92, 246, 0.8)'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'right'
                    }
                }
            }
        });
    }

    /**
     * 初始化生成趋势图
     */
    initGenerationTrendChart() {
        const ctx = document.getElementById('generationTrendChart');
        if (!ctx) return;

        this.charts.generationTrend = new Chart(ctx, {
            type: 'line',
            data: {
                labels: this.getLast7Days(),
                datasets: [{
                    label: '生成数量',
                    data: this.generateTrendData(),
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取最近7天的日期
     */
    getLast7Days() {
        const days = [];
        for (let i = 6; i >= 0; i--) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            days.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
        }
        return days;
    }

    /**
     * 生成趋势数据
     */
    generateTrendData() {
        const data = [];
        for (let i = 0; i < 7; i++) {
            data.push(Math.floor(Math.random() * 10) + 5);
        }
        return data;
    }

    /**
     * 关闭模态框
     */
    closeModal(modalId) {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.remove();
        }
    }

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        const colors = {
            success: 'bg-green-500',
            error: 'bg-red-500',
            warning: 'bg-yellow-500',
            info: 'bg-blue-500'
        };

        notification.className = `fixed top-4 right-4 ${colors[type]} text-white px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full`;
        notification.textContent = message;

        document.body.appendChild(notification);

        setTimeout(() => {
            notification.classList.remove('translate-x-full');
        }, 100);

        setTimeout(() => {
            notification.classList.add('translate-x-full');
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }

    /**
     * 销毁实例
     */
    destroy() {
        // 销毁图表
        Object.keys(this.charts).forEach(key => {
            if (this.charts[key]) {
                this.charts[key].destroy();
            }
        });
    }
}

// 页面加载完成后初始化报告生成管理器
document.addEventListener('DOMContentLoaded', function() {
    window.reportGenerationManager = new ReportGenerationManager();
});

// 监听页面卸载事件
window.addEventListener('beforeunload', function() {
    if (window.reportGenerationManager) {
        window.reportGenerationManager.destroy();
    }
});